<template>
  <div class="detail-container">
    <!-- 左侧：课程详情 -->
    <div class="left-part">
      <div class="course-detail">
        <h1>课程详情</h1>
        <!-- 课程的详细信息展示 -->
        <p>课程名称: {{ course.name }}</p>
        <p>教师: {{ course.teacherId }}</p>
        <p>学分: {{ course.credit }}</p>
        <p>年级: {{ course.grade }}</p>
        <p>时间: {{ course.time }}</p>
        <p>地点: {{ course.location }}</p>
        <p>考试日期: {{ course.examDate }}</p>
      </div>
    </div>

    <!-- 右侧：课程资源、试卷库、习题库 -->
    <div class="right-part">
      <!-- 课程资源部分 -->
      <div class="coursemanage-container">
        <div class="section">
          <h3 class="favorites-title">课程资源</h3>
          <div class="folder">
            <h4 class="folder-title">资源列表</h4>
            <div class="files-container">
              <div
                class="file-item"
                v-for="(note, noteIndex) in courseResources.notes"
                :key="noteIndex"
              >
                <h4 class="note-title">{{ note.title }}</h4>
                <p class="note-content">{{ note.content }}</p>
                <p class="note-file-id">文件ID: {{ note.id }}</p>

                <button @click="openFile(note)" class="open-file-btn">打开文件</button>
                <button @click="downloadFile(note.id)" class="download-btn">下载</button>
              </div>
              <div class="no-files" v-if="courseResources.notes.length === 0">没有文件</div>
            </div>
            <input
              type="file"
              @change="handleFileSelect($event)"
              class="file-input"
              accept=".txt,.doc,.pdf"
            />
            <button @click="uploadFile('addcourseware')" class="add-file-btn">添加文件</button>
          </div>
        </div>
      </div>

      <!-- 历年试卷库部分 -->
      <div class="coursemanage-container">
        <div class="section">
          <h3 class="favorites-title">历年试卷库</h3>
          <div class="folder">
            <h4 class="folder-title">试卷列表</h4>
            <div class="files-container">
              <div
                class="file-item"
                v-for="(note, noteIndex) in examPapers.notes"
                :key="noteIndex"
              >
                <h4 class="note-title">{{ note.title }}</h4>
                <p class="note-content">{{ note.content }}</p>
                <p class="note-file-id">文件ID: {{ note.id }}</p>

                <button @click="openFile(note)" class="open-file-btn">打开文件</button>
                <button @click="downloadFile(note.id)" class="download-btn">下载</button>
              </div>
              <div class="no-files" v-if="examPapers.notes.length === 0">没有文件</div>
            </div>
            <input
              type="file"
              @change="handleFileSelect($event)"
              class="file-input"
              accept=".txt,.doc,.pdf"
            />
            <button @click="uploadFile('addtest')" class="add-file-btn">添加文件</button>
          </div>
        </div>
      </div>

      <!-- 习题库部分 -->
      <div class="coursemanage-container">
        <div class="section">
          <h3 class="favorites-title">习题库</h3>
          <div class="folder">
            <h4 class="folder-title">习题列表</h4>
            <div class="files-container">
              <div
                class="file-item"
                v-for="(note, noteIndex) in exerciseBank.notes"
                :key="noteIndex"
              >
                <h4 class="note-title">{{ note.title }}</h4>
                <p class="note-content">{{ note.content }}</p>
                <p class="note-file-id">文件ID: {{ note.id }}</p>

                <button @click="openFile(note)" class="open-file-btn">打开文件</button>
                <button @click="downloadFile(note.id)" class="download-btn">下载</button>
              </div>
              <div class="no-files" v-if="exerciseBank.notes.length === 0">没有文件</div>
            </div>
            <input
              type="file"
              @change="handleFileSelect($event)"
              class="file-input"
              accept=".txt,.doc,.pdf"
            />
            <button @click="uploadFile('addexercise')" class="add-file-btn">添加文件</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { useRoute } from 'vue-router'; // 用于获取路由参数

export default {
  name: "CourseManage",
  setup() {
    const route = useRoute(); // 获取当前路由参数
    const courseId = route.params.courseId; // 从路由参数中获取 courseId
    return { courseId }; // 返回给组件使用
  },
  data() {
    return {
      baseURL: "http://localhost:8085", // Base API URL
      course: {}, // 课程详情数据
      courseResources: { name: '课程资源', notes: [] }, // 课程资源数据
      examPapers: { name: '历年试卷库', notes: [] }, // 历年试卷数据
      exerciseBank: { name: '习题库', notes: [] }, // 习题库数据
      selectedFile: null, // 存储用户选择的文件
      id : 1,
    };
  },
  methods: {
    // 处理文件选择
    handleFileSelect(event) {
      const file = event.target.files[0];
      if (file) {
        this.selectedFile = file;
      }
    },

    // 上传文件
    uploadFile(endpoint) {
      if (!this.selectedFile) {
        console.error('没有选择文件');
        return;
      }

      const formData = new FormData();
      formData.append('file', this.selectedFile);
      formData.append('courseid', this.courseId); // 使用从路由中获取的 courseId

      axios.post(`${this.baseURL}/courseresource/${endpoint}`, formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })
      .then(() => {
        alert("文件上传成功");
        this.selectedFile = null; // 清空选择的文件
        this.fetchCourseData(); // 重新获取数据
      });
    },

    // 下载文件
    downloadFile(fileId) {
      axios.get(`${this.baseURL}/courseresource/download`, {
        params: { fileId: fileId },
        responseType: 'blob'
      })
      .then(response => {
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        let fileName = response.headers['content-disposition'].split('filename=')[1].replace(/['"]/g, '');
        link.href = url;
        link.setAttribute('download', decodeURIComponent(fileName));
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      });
    },

    // 获取课程数据
    fetchCourseData() {
      axios.get(`${this.baseURL}/courseresource/viewware`, { params: { courseid: this.id } })
      .then(response => {
        this.courseResources.notes = response.data.map(item => ({
          title: item.fileName,
          content: item.fileDescription,
          id: item.fileId
        }));
      });

      axios.get(`${this.baseURL}/courseresource/viewtest`, { params: { courseid: this.id} })
      .then(response => {
        this.examPapers.notes = response.data.map(item => ({
          title: item.fileName,
          content: item.fileDescription,
          id: item.fileId
        }));
      });

      axios.get(`${this.baseURL}/courseresource/viewexercise`, { params: { courseid: this.id } })
      .then(response => {
        this.exerciseBank.notes = response.data.map(item => ({
          title: item.fileName,
          content: item.fileDescription,
          id: item.fileId
        }));
      });
    },

    // 获取课程详情
    async fetchCourseDetail() {
      const courseId = this.$route.params.courseId; // 从路由参数中获取 courseId
      const response = await axios.get(`${this.baseURL}/course/detail/${courseId}`);
      if (response.data) {
        this.course = response.data; // 存储课程详情数据
        this.id = response.id
      } else {
        console.error("无法获取课程详情");
      }
    }
  },
  mounted() {
    this.fetchCourseDetail(); // 获取课程详情
    this.fetchCourseData(); // 获取课程相关资源数据
  }
};
</script>

<style scoped>
.detail-container {
  display: flex;
  justify-content: space-between;
}

.left-part {
  width: 28%;
}

.right-part {
  width: 70%;
}

.course-detail {
  padding: 20px;
}

.section {
  padding: 10px;
  background-color: #f9f9f9;
  border: 1px solid #ddd;
  border-radius: 5px;
  margin-bottom: 20px;
}

.favorites-title {
  font-size: 20px;
  color: #333;
  margin-bottom: 10px;
}

.folder {
  margin: 10px;
  padding: 10px;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.folder-title {
  font-size: 18px;
  color: #333;
}

.files-container {
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 5px;
}

.file-item {
  border-bottom: 1px solid #eee;
  padding: 5px 0;
}

.note-title {
  font-size: 16px;
  color: #555;
}

.note-content {
  font-size: 14px;
  color: #777;
}

.note-file-id {
  font-size: 12px;
  color: #888;
}

.open-file-btn,
.download-btn {
  background-color: #f44336;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 5px 10px;
  cursor: pointer;
  margin-top: 5px;
}

.no-files {
  font-size: 14px;
  color: #999;
  text-align: center;
  margin-top: 10px;
}

.file-input {
  margin-top: 10px;
}

.add-file-btn {
  margin-top: 5px;
  background-color: #4CAF50;
}

.add-file-btn:hover {
  background-color: #388E3C;
}
</style>
